package org.pro.Net;

import org.pro.Model.Shot;
import org.pro.Model.Tank;
import org.pro.Model.WarData;
import org.pro.View.GameView;
import org.pro.utils.Utils;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {

    public ObjectOutputStream out;
    public ObjectInputStream in;
    public Socket socket;
    public boolean isConnected=false;
    public  volatile WarData warData;
    public GameView win;
    Tank tank;
    public int id;
    //1.先进行与服务器的连接
    public boolean contect(String ip,int Port)
    {
        try{
            socket=new Socket(ip,Port);
            out=new ObjectOutputStream(socket.getOutputStream());
            in=new ObjectInputStream(socket.getInputStream());
            isConnected=true;
            return true;
        }catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    //运行这俩个线程
    public void run() {
        // 创建并启动接收消息线程
        new Thread(() -> RecMessage()).start();
        // 创建并启动发送消息线程
    }

    //2.发消息线程用这个代替即可呗！天才哦
    //2.发消息线程
    public void keeper() {
        if (id == 0) {
            tank = warData.userTank;
        } else {
            tank = warData.enemyTank;
        }
        if (tank == null) return; // Ensure tank is not null
        System.out.println("监听开始咯！");
        MouseAdapter adapter = new MouseAdapter() {
            public void mouseMoved(MouseEvent e) {
                if (!warData.userTank.Destroyed) {
                    double x = (double) (e.getX() - 9);
                    double y = (double) (e.getY() - 36);
                    Natway msg = Natway.creatTankdir(Utils.ppDir(tank.x, tank.y, x, y) + 90.0,id);
                    sendMessage(msg); // Send the message
                }
            }

            public void mousePressed(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    if (!tank.Destroyed) {
                        Natway msg = Natway.creatShoot(id);
                        sendMessage(msg); // Send the message
                    }
                }
            }
        };

        win.addMouseListener(adapter);
        win.addMouseMotionListener(adapter);
        win.addMouseWheelListener(adapter);

        win.panel.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (tank.Destroyed) {
                    tank.moving = false;
                    Natway msg = new Natway();
                    msg = Natway.creatTankmove(false, "1", id);
                    sendMessage(msg);
                } else {
                    Natway msg = new Natway();
                    switch (e.getKeyChar()) {
                        case 'A':
                        case 'a':
                            tank.moving=true;
                            msg = Natway.creatTankmove(true, "左", id);
                            sendMessage(msg);
                            break;
                        case 'D':
                        case 'd':
                            tank.moving=true;
                            msg = Natway.creatTankmove(true, "右", id);
                            sendMessage(msg);
                            break;
                        case 'S':
                        case 's':
                            tank.moving=true;
                            msg = Natway.creatTankmove(true, "下", id);
                            sendMessage(msg);
                            break;
                        case 'W':
                        case 'w':
                            tank.moving=true;
                            msg = Natway.creatTankmove(true, "上", id);
                            sendMessage(msg);
                            break;
                        case ' ':
                            break;
                        case KeyEvent.VK_ESCAPE:
                            break;
                    }// Send the message
                }
            }
                public void keyReleased(KeyEvent e) {
                    switch (e.getKeyChar()) {
                        case 'A':
                        case 'D':
                        case 'S':
                        case 'W':
                        case 'a':
                        case 'd':
                        case 's':
                        case 'w':
                            tank.moving=false;
                            Natway msg=Natway.creatTankmove(false,"2",id);
                            sendMessage(msg);
                            break;
                        default:
                            break;
                    }
                }

        });
    }
    // 发送消息的辅助方法
    public void sendMessage(Natway msg) {
            try {
                if(msg.type== Natway.MessageType.TANK_MOVE)
                    System.out.println("坦克状态:"+msg.moving);
                out.writeObject(msg);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    public void RecMessage()
    {
        while(isConnected)
        {
             try {
            Object obj = in.readObject();
            if (obj instanceof Natway) {
                Natway msg = (Natway) obj;
                if (msg.type == Natway.MessageType.STATE) {
                    updateLocalState(msg.warData,msg.dt);
                }
                else if(msg.type==Natway.MessageType.READY)
                {
                    System.out.println("wardata并不为空的啊！！！！");
                    SwingUtilities.invokeLater(() -> {
                        this.id = msg.playerid;
                        this.warData = msg.warData;
                        this.win = new GameView(this.warData);
                        win.setVisible(true); // 确保窗口可见
                        keeper();
                    });
                    sendMessage(msg);
                }
                // 根据msg的内容进行相应处理
                // 比如，如果是坦克移动指令或者其他处理
            } else {
                // 处理其他类型的消息
                System.out.println("Received unknown object: " + obj);
            }
        } catch (IOException e) {
            e.printStackTrace();
            break; // 如果发生IOException，可能连接已经断开，退出循环
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        }
    }
    public void updateLocalState(WarData serverData,float dt) {
        // 只更新需要同步的字段
        SwingUtilities.invokeLater(() -> {
            win.updateWarData(serverData); // 更新 GameView 的 warData
            win.update(dt);
        });
    }
}
